#!/usr/bin/python
# -*- coding: UTF-8 -*-

import math
import time
import pandas as pd


class Converter(object):

    def run(self, html="bookmark.html"):
        print("开始分析表格...")
        links, tags = self.excel(xls="bookmark.xlsx", sheet="我的书签", debug=False)
        print("开始生成书签...")
        ts = int(time.time())
        with open(html, 'w', encoding="utf-8") as f:
            f.write("<!DOCTYPE NETSCAPE-Bookmark-file-1>\n")
            f.write("<!-- This is an automatically generated file.\n")
            f.write("     It will be read and overwritten.\n")
            f.write("     DO NOT EDIT! -->")
            f.write("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">\n")
            f.write("<TITLE>Bookmarks</TITLE>\n")
            f.write("<H1>Bookmarks</H1>\n")
            f.write("<DL><p>\n")
            f.write("    <DT><H3 ADD_DATE=\"%d\" LAST_MODIFIED=\"0\" PERSONAL_TOOLBAR_FOLDER=\"true\">书签栏</H3>\n" % ts)
            f.write("    <DL><p>\n")

            f.write("    </DL><p>\n")
            f.write("</DL><p>\n")
            f.flush()
        print("已完成~\n")
        print("请在Chrome地址栏输入 chrome://bookmarks/ , 点击右上角 三个小点 图标, 选择导入书签.")
        pass

    def sort(self, level, tags, links):
        # 打印分割线
        print(level, "#" * 100)
        # 本级标签
        tag_set = tags[level]
        print(tag_set)
        # 临时存储
        tmp_link_list = list()
        multi_level_tag = False
        # 开始查找
        for tag in tag_set:
            for link in links:
                if len(link["标签"]) < level + 1:
                    continue
                if tag == link["标签"][level]:
                    tmp_link_list.append(link)
                    if len(link["标签"]) > level + 1:
                        multi_level_tag = True
        if len(tmp_link_list) > 0 and multi_level_tag:
            tmp_link_list.extend(self.sort(level + 1, tags, tmp_link_list))
        return tmp_link_list

    @staticmethod
    def excel(xls, sheet, debug=False):
        if debug:
            print("文件名&页名: ", xls, sheet)
        # 读取excel中的sheet页,返回DataFrame对象
        df = pd.read_excel(xls, sheet_name=sheet)
        if debug:
            print("表格预览\n", df.head())
        # 记录每条有效数据
        link_list = list()
        # 标签最大级数
        tag_num = 5
        # 记录每级标签集合
        tag_tree = list()
        for i in range(tag_num):
            # 初始化
            tag_tree.append(set())
        # 遍历数据
        for index, row in df.iterrows():
            # 打印分割线
            print(index, "-" * 100)
            # 跳过无效记录
            if (isinstance(row["链接"], float) and math.isnan(row["链接"])) \
                    or isinstance(row["名称"], float) and math.isnan(row["名称"]):
                print("跳过无效记录!\n")
                continue
            # 组装链接和名称
            link_dat = {
                "链接": row["链接"],
                "名称": row["名称"],
            }
            # 组装标签
            link_tags = list()
            for i in range(1, tag_num + 1):
                # 获取对应级别的标签
                tag = row["标签-%d" % i]
                # 判断标签是否合法
                if isinstance(tag, float) and math.isnan(tag):
                    continue
                # 加入列表
                link_tags.append(tag)
                # 加入集合
                tag_tree[i - 1].add(tag)
            link_dat.update({"标签": link_tags})
            print(link_dat)
            link_list.append(link_dat)
        return link_list, tag_tree


if __name__ == '__main__':
    inst = Converter()
    inst.run()
    pass
